package com.haoyeteng.sxbd.modular.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haoyeteng.sxbd.core.constant.SxbdConstants;
import com.haoyeteng.sxbd.core.exception.SxbdException;
import com.haoyeteng.sxbd.core.util.DateUtil;
import com.haoyeteng.sxbd.core.util.GeometryUtil;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.dao.WarnMapper;
import com.haoyeteng.sxbd.modular.business.model.Account;
import com.haoyeteng.sxbd.modular.business.model.Coordinate;
import com.haoyeteng.sxbd.modular.business.model.Product;
import com.haoyeteng.sxbd.modular.business.model.Warn;
import com.haoyeteng.sxbd.modular.business.service.IAccountService;
import com.haoyeteng.sxbd.modular.business.service.ICoordinateService;
import com.haoyeteng.sxbd.modular.business.service.IProductService;
import com.haoyeteng.sxbd.modular.business.service.IWarnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报警表 服务实现类
 * </p>
 *
 * @author haoyeteng123
 * @since 2019-07-06
 */
@Service
public class WarnServiceImpl extends ServiceImpl<WarnMapper, Warn> implements IWarnService {

    @Autowired
    private IAccountService accountService;

    @Autowired
    private ICoordinateService coordinateService;

    @Autowired
    private IProductService productService;

    /**
     * 报警分页查询
     * @param page 分页
     * @param params 参数
     * @return List<map>
     */
    @Override
    public List<Map<String, Object>> selectWarns(Page<Warn> page, Map<String,Object> params){
        return this.baseMapper.selectWarns(page, params);
    }

    @Override
    public List<Map<String, Object>> getWarns(String serviceType, String accountName) {
        //TODO 接口不通, 使用临时数据
        //String json = HttpUtils.get("http://49.4.94.172:9099/shxcors/account/allpositon");
        String json = "[{Longitude:109.12343,Latitude:35.432212,Login:\"SHY0001/shy800181\"}," +
                "{Longitude:189.92343,Latitude:35.832212,Login:\"SHY001/shy800102\"}," +
                "{Longitude:189.92343,Latitude:35.832212,Login:\"SHY8082/shy800101\"}]";
        JSONArray jsonArray = JSONObject.parseArray(json);
        if(ToolUtil.isEmpty(jsonArray)) {
            throw new SxbdException(400,"数据不存在");
        }
        List<Map<String, Object>> list = new ArrayList<>();
        if(jsonArray.size()>0){
            for(int i=0; i<jsonArray.size(); i++){
                JSONObject jsonData = JSONObject.parseObject(jsonArray.getString(i));
                //位置坐标点
                Double longitude = jsonData.getDouble("Longitude");
                Double latitude = jsonData.getDouble("Latitude");
                Point2D.Double point = new Point2D.Double(longitude, latitude);
                //账号
                String login = jsonData.getString("Login");
                String[] strings = login.split("/");
                String account = strings[1].toLowerCase();
                Account accountVo = accountService.selectOne(new EntityWrapper<Account>().eq("account", account)
                        .eq(ToolUtil.isNotEmpty(serviceType),"service_type",serviceType)
                        .like(ToolUtil.isNotEmpty(accountName),"account",accountName));
                if (ToolUtil.isEmpty(accountVo)) {
                    continue;
                }
                if (ToolUtil.isEmpty(accountVo)) {
                    throw new SxbdException("未获取到对应数据：" + jsonArray.getString(i) + "的账号信息！");
                }
                if (ToolUtil.isEmpty(accountVo.getEleFenceId())) {
                    throw new SxbdException("未获取到对应账号：" + accountVo.getAccount() + "的围栏信息！");
                }
                Map<String, Object> accountMap = accountService.selectByAccountId(accountVo.getAccountId());

                //围栏坐标点
                List<Coordinate> coordinates = coordinateService.selectList(new EntityWrapper<Coordinate>().eq("ele_fence_id"
                        , accountVo.getEleFenceId()).orderBy("point_no"));
                if (ToolUtil.isEmpty(coordinates)) {
                    throw new SxbdException("未获取到围栏Id" + accountVo.getEleFenceId() + "对应的坐标点！");
                }
                List<Point2D.Double> points = new ArrayList<>();
                for (Coordinate coordinate : coordinates) {
                    points.add(new Point2D.Double(coordinate.getLng().doubleValue(),coordinate.getLat().doubleValue()));
                }
                //是否超出范围
                boolean ifOutRange = !GeometryUtil.isPtInPoly(point, points);
                Map<String, Object> map = new HashMap<>(16);
                if (ifOutRange){
                    Product product = productService.selectOne(new EntityWrapper<Product>().eq("service_type", accountVo.getServiceType().toUpperCase()));
                    if (ToolUtil.isEmpty(product)) {
                        throw new SxbdException("获取对应服务类型：" + accountVo.getServiceType() + "失败！");
                    }
                    map.put("account", account);
                    map.put("accountId", accountVo.getAccountId());
                    map.put("eleFenceId", accountVo.getEleFenceId());
                    map.put("lng", longitude);
                    map.put("lat", latitude);
                    map.put("productName", product.getProductName());
                    //所属机构
                    map.put("organName", accountMap.get("organName"));
                    map.put("warnType", SxbdConstants.WARN_TYPE_OUT_RANGE);
                    map.put("warnDate", DateUtil.getTime());
                    list.add(map);
                }
            }
        }
        return list;
    }

}
